/** 
 * @description web本地数据库工具(indexedDB)
 * @author c-jw
 * @time 2020年3月31日 15:05:49
 */

export default function (callback, dbname = 'ApiDoc', version = 1) {
  if (!window.indexedDB) {
    window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.")
  }
  var IDB = indexedDB.open(dbname, version);
  IDB.addEventListener('upgradeneeded', e => {
    // 要创建一个对象仓库必须在upgradeneeded事件中，而upgradeneeded事件只会在版本号更新的时候触发，
    // 这是因为IndexedDB API中不允许数据库中的数据仓库在同一版本中发送变化
    const db = e.target.result;
    //创建文档缓存仓库(当前编辑的文档)
    var Cache = db.createObjectStore('cache', {
      keyPath: 'id',
      unique: true //名称唯一
    });
    //创建文档仓库
    var Doc = db.createObjectStore('doc', {
      keyPath: 'name', //主键
      // autoIncrement: true //自增
    });
    // 文档索引 (名称索引)
    Doc.createIndex('name', 'name', {
      unique: true, //名称唯一
    });
    // // 文档索引 (名称索引)
    // Doc.createIndex('name', 'name', {
    //   unique: true, //名称唯一
    //   keyPath: 'name', //主键
    // });
    // 文档索引 (名称+描述的混合索引)
    Doc.createIndex(
      'like',
      ['name', 'desc'], {
        unique: false
      });
    console.log('初始化对象仓库');
  })
  IDB.addEventListener('success', e => {
    console.log("%c %s %O", "color:green", "[数据库连接成功]", e.target.result);
    let DB = {
      $db: e.target.result,
      store: function (storeName, mode) {
        return this.$db.transaction(storeName, mode || 'readwrite').objectStore(storeName);
      },
      put: function (storeName, data, queryCallback) {
        var res = this.store(storeName).put(data);
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      },
      find: function (storeName, queryCallback) {
        let res = this.store(storeName).openCursor(null, 'prev');
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      },
      del: function (storeName, id, queryCallback) {
        let res = this.store(storeName).delete(id);
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      }
    }
    let Doc = {
      $db: e.target.result,
      store: function (storeName, mode) {
        return this.$db.transaction(storeName, mode || 'readwrite').objectStore(storeName);
      },
      put: function (data, queryCallback) {
        if (!data || !data.name) {
          return
        }
        data.updateTime = new Date().toLocaleString();
        var res = this.store("doc").put(data);
        res.onerror = function (err) {
          console.log(err);
        }
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      },
      get: function (primaryKey, queryCallback) {
        let res = this.store("doc").get(primaryKey);
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      },
      find: function (queryCallback) {
        let res = this.store("doc").openCursor(null, 'prev');
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      },
      del: function (id, queryCallback) {
        let res = this.store("doc").delete(id);
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      },
      // 缓存相关
      cache: function (data) {
        if (data) {
          data.id = 0;
          return this.store("cache").put(data)
        } else {
          return this.store("cache").get(0);
        }
      },
      cacheDel: function (queryCallback) {
        let res = this.store("cache").delete(0);
        queryCallback && (res.onsuccess = queryCallback);
        return res;
      }
    }
    callback && callback(Doc, DB);
  });
  IDB.addEventListener('error', e => {
    console.log("%c %s %O", "color:red", "[连接数据库失败]", e);
  });
  return IDB;
}